// 导入 express 模块
const express = require("express");
const userModel = require("../../models/userModel");
const md5 = require("md5");
const jwt = require("jsonwebtoken");
const { secret } = require("../../config/config");

// 路由
var router = express.Router();

// 路由规则
router.post("/login", (req, res) => {
  // 获取用户名和密码
  let { username, password } = req.body;

  // 查询数据库
  userModel.findOne(
    {
      username: username,
      password: md5(password),
    },
    "techfengs",
    (err, data) => {
      if (err) {
        // console.log("查询数据库失败");
        res.json({
          code: "2001",
          msg: "查询数据库失败",
          data: null,
        });
        return;
      }
      console.log("data");
      if (data == null) {
        // console.log("用户名或密码错误~~");
        res.json({
          code: "2002",
          msg: "用户名或密码错误",
          data: null,
        });
        return;
      }
      // console.log(data);
      let token = jwt.sign(
        {
          username: data.username,
          _id: data._id,
        },
        secret,
        {
          expiresIn: 60 * 60 * 24 * 7,
        },
      );
      res.json({
        code: "0000",
        msg: "登录成功",
        data: token,
      });
      return;
    },
  );
});

// 暴露端口
module.exports = router;
